package com.kingdee.eas.custom.common.server;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.framework.ejb.EJBFactory;
import com.kingdee.eas.framework.report.util.DBUtil;
import com.kingdee.eas.framework.report.util.SqlParams;
import com.kingdee.util.db.SQLUtils;

public class DbUtils {

	public static void executeIntoTempTable(Context ctx, String sql,
			String tempTable, SqlParams params) throws BOSException {

		Connection conn = null;
		Statement stmt = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ResultSetMetaData rsmd = null;
		try {
			conn = EJBFactory.getConnection(ctx);
			stmt = conn.createStatement();

			StringBuffer buffer = new StringBuffer("/*dialect*/SELECT * FROM (");
			buffer.append(sql + ") temp where 1=0");

			pstmt = conn.prepareStatement(buffer.toString());
			if (params != null && params.size() > 0) {
				params.putToStatement(pstmt);
			}

			rs = pstmt.executeQuery();
			rsmd = rs.getMetaData();

			String createTableSql = DBUtil.getKSQLDialect()
					.buildCreateTableString(tempTable, rsmd);
			stmt.execute(createTableSql);

			buffer = new StringBuffer("/*dialect*/INSERT INTO ");
			buffer.append(tempTable);
			buffer.append(" ");
			buffer.append(sql);

			DBUtil.executeUpdate(buffer.toString(), params, conn);
		} catch (SQLException e) {
			throw new BOSException(e);
		} finally {
			SQLUtils.cleanup(conn);
			SQLUtils.cleanup(rs, pstmt);
		}
	}
}
